package com.demo.common.utils.compare;

import org.apache.commons.lang3.StringUtils;
import org.springframework.util.Assert;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.time.temporal.TemporalAccessor;

/**
 * @Author xinge001
 * @Date 2024/03/18 10:40
 * @Description 时间工具类
 * @Version 1.0.0
 */
public class DateTimeUtils {

    /**
     * 通用日期时间格式
     */
    private static DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    /**
     * 通用日期格式
     */
    private static DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    /**
     * 通用时间格式
     */
    private static DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss");

    private DateTimeUtils() {
    }

    /**
     * 获取yyyy-mm-dd HH:mm:ss格式时间
     */
    public static String getCommonDateOrTime(TemporalAccessor temporalAccessor) {
        Assert.notNull(temporalAccessor, "temporalAccessor参数不能为null");
        if (temporalAccessor instanceof LocalDateTime) {
            return dateTimeFormatter.format(temporalAccessor);
        }
        if (temporalAccessor instanceof LocalDate) {
            return dateFormatter.format(temporalAccessor);
        }
        if (temporalAccessor instanceof LocalTime) {
            return timeFormatter.format(temporalAccessor);
        }
        //找不到就用日期时间格式
        return dateTimeFormatter.format(temporalAccessor);
    }

    /**
     * 通用字符串转localDateTime，格式yyyy-MM-dd HH:mm:ss
     * {@link DateTimeUtils#convertStr(String, DateTimeFormatter)}
     * @return 字符串为空或者无法转换返回null
     */
    public LocalDateTime convertCommonStr(String time) {
        return convertStr(time, dateTimeFormatter);
    }

    /**
     * 字符串转localDateTime
     * @param time
     * @param formatter
     * @return 字符串为空或者formatter为空或者无法转换返回null
     */
    public LocalDateTime convertStr(String time, DateTimeFormatter formatter) {
        if (StringUtils.isBlank(time) || formatter == null) {
            return null;
        }
        try {
            return LocalDateTime.parse(time, dateTimeFormatter);
        } catch (DateTimeParseException e) {
            return null;
        }
    }


}
